import operate from '@dfeidao/atom-nodejs/db/operate';
import query from '@dfeidao/atom-nodejs/db/query';
import uuid from 'uuid';
interface Message {
	formid: string;
	client_type: string;
	productid: string;
	filter1?: {
		group_name: string;
		group_number: string;
		formname?: string;	// 功能名称
		package_no?: string; // 页面编号
		package_name?: string;// 页面名称”：弹窗7返回参数;
		package_path?: string; // 页面地址：弹窗7返回参数;
	};
	filter2?: {
		del?: string[]; // 删除参数
		inst_data?: Array<{}>; // 添加参数
	};
}
interface PubFormCode {
	code: string;			// 编码
	action_keyword: string;	// 控制点关键字
	action_name: string;	// 控制点名称
}
// 依据功能号和编码删除 功能定义控制点pub_form_code数据
export default async function atom(msg: Message, action_id: string, session_id: string, spaceid: string) {
	// 功能定义库 pub_form
	// 根据formname,package_no 判断是否重复
	const { exec, prepare } = query(action_id, session_id, '12');
	if (msg.filter1.formname) {
		prepare('pub_form', ['_id'], { formname: msg.filter1.formname, productid: msg.productid }, 200, 1, [], []);
		const [data] = await exec();
		if (data.length !== 0) {
			return 'repeat';
		}
	}
	// 不重复根据formid修改数据
	const { exec: e3, insert: p3, update, del } = operate(action_id, session_id, '12');
	update('pub_form', { formid: msg.formid, productid: msg.productid }, msg.filter1);
	// 如果存在删除原始功能点则删除
	if (msg.filter2.del) {
		Array.from(msg.filter2.del).forEach((v: string) => {
			del('pub_form_code', { code: v, formid: msg.formid, productid: msg.productid });
		});
	}
	// 如果存在新增功能点则新增
	if (msg.filter2.inst_data) {
		Array.from(msg.filter2.inst_data).forEach((v: PubFormCode) => {
			p3('pub_form_code', {
				_id: uuid(),
				formid: msg.formid,
				code: v.code,
				action_keyword: v.action_keyword,
				action_name: v.action_name,
				productid: msg.productid,
				source_flag: 0
			});
		});
	}
	const ret = await e3();
	if (ret.code === 1) {
		return 'success';
	} else {
		return 'fail';
	}
}
